package com.ebupt.migu.music.autoTri.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ebupt.migu.music.autoTri.Entity.*;
import com.ebupt.migu.music.autoTri.Enum.CatalogInfoEnum;
import com.ebupt.migu.music.autoTri.Enum.RelationEnum;
import com.ebupt.migu.music.autoTri.Mapper.AutoTouchOffMapper;
import com.ebupt.migu.music.autoTri.util.CheckUtil;
import com.ebupt.migu.music.autoTri.util.fileUtil;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.common.util.JsonUtils;
import com.ebupt.migu.music.schedule.mapper.PopupStatsMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author xuhongsong
 * @version 1.0
 * @date 2020/10/15 17:18
 */
@Service
@Component
@Slf4j
public class AsyncService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AutoTouchOffMapper autoTouchOffMapper;
    @Autowired
    private PopupStatsMapper popupStatsMapper;

    /**
     * 晚上的发送截至时间
     */
    @Value("${followSinger.send-end-times}")
    private String SEND_END_TIME;

    public static AsyncService asyncService;

    // 按每29个一组分割
    private static final Integer MAX_NUMBER = 29;

    private static String POPUP_STATS_MIN = "POPUP_STATS_MIN";

    private static String POPUP_STATS_MIN_MSI = "POPUP_STATS_MIN_MSI";
    private static String POPUP_STATS_MIN_ACT = "POPUP_STATS_MIN_ACT";

    @PostConstruct
    public void init() {
        asyncService = this;
    }

    /**
     * 新增编目接口返回数据
     *
     * @param consumerRecord
     */
    @Async
    public void insertKafkaofCatalogInfo(ConsumerRecord<String, String> consumerRecord) {
        Map resultMap = JsonUtils.json2Obj(consumerRecord.value(), Map.class);
        Optional.ofNullable(resultMap).map(u -> resultMap.get("action")).ifPresent((value) -> {
            if (mapGetString(resultMap, "action").equals("0")) {
                log.info("获取新增编目接口返回数据:{}", consumerRecord.value());
                CatalogInfo catalogInfo = CatalogInfo.builder().copyrightId(mapGetString(resultMap, "copyrightID"))
                    .songId(mapGetString(resultMap, "songID")).songName(mapGetString(resultMap, "songName"))
                    .type(CatalogInfoEnum.TOSONG.getCode()).build();
                autoTouchOffMapper.addCatalogInfo(catalogInfo);
            }
        });
    }

    /**
     * mv产品id入库
     *
     * @param consumerRecord
     */
    @Async
    public void insertKafkaofdeployMv(ConsumerRecord<String, String> consumerRecord) {
        log.info("门户接收统一曲库分发MV接口:{}", consumerRecord.value());
        Map resultMap = JsonUtils.json2Obj(consumerRecord.value(), Map.class);
        Optional.ofNullable(resultMap).map(u -> resultMap.get("action")).ifPresent((value) -> {
            if (mapGetString(resultMap, "action").equals("0")) {
                log.info("门户接收统一曲库分发MV接口:{}", consumerRecord.value());
                CatalogInfo catalogInfo = CatalogInfo.builder()
                    .copyrightId(null != mapGetString(resultMap, "copyrightID")
                        ? mapGetString(resultMap, "copyrightID").substring(0, 11)
                        : mapGetString(resultMap, "copyrightID"))
                    .productId(mapGetString(resultMap, "contentID"))
                    .validateDate(strToDate(mapGetString(resultMap, "validateDate")))
                    .invalidateDate(strToDate(mapGetString(resultMap, "invalidateDate")))
                    .type(CatalogInfoEnum.TOMV.getCode()).build();
                autoTouchOffMapper.addCatalogInfo(catalogInfo);
            }
        });
    }

    /**
     * 曲库
     *
     * @param consumerRecord
     */
    @Async
    public void insertWirelessProduct(ConsumerRecord<String, String> consumerRecord) {
        Map resultMap = JsonUtils.json2Obj(consumerRecord.value(), Map.class);
        Optional.ofNullable(resultMap).map(u -> resultMap.get("action")).ifPresent((value) -> {
            if (mapGetString(resultMap, "action").equals("0")) {
                String contentId = mapGetString(resultMap, "contentID");
                // contentId 前11位是版权ID，最后18位是产品ID
                log.info("获取统一曲库分发（振、全、随:{}  contentId:{}", consumerRecord.value(), contentId);
                if (StringUtils.isNotBlank(contentId) && contentId.length() > 29) {
                    CatalogInfo catalogInfo = CatalogInfo.builder().copyrightId(contentId.substring(0, 11))
                        .productId(contentId.substring(contentId.length() - 18))
                        .type(CatalogInfoEnum.TOWIRELESSPRODUCT.getCode()).build();
                    autoTouchOffMapper.addCatalogInfo(catalogInfo);
                }
            }
        });
    }

    public void insertPopupData(ConsumerRecord<String, String> consumerRecord) {
        if (isEffectiveDate()) {
            return;
        }
        log.info("获取kafka中变色龙真实的实时数据:{}", consumerRecord);
        Optional.ofNullable(consumerRecord.value()).ifPresent(message -> {
            log.info("kafka中获取到的变色龙实时数据:{}", message);
            // 第一步：截取字符串并转换成集合
            List<String> list = new ArrayList<>();
            String[] str = null;
            if (message.contains("\r\n") || message.contains("\r")) {
                message = message.replaceAll("\r", "A==A").replaceAll("\n", "");
                str = message.split("A==A");
                list = Arrays.asList(str);
            } else {
                list = Arrays.asList(message);
            }
            // 第三步：转换成对象集合
            List<PopupLog> logList = new ArrayList<>();
            list.forEach(spl -> {
                try {
                    PopupLog oblog = new PopupLog(spl);
                    logList.add(oblog);
                } catch (Exception e) {
                    log.error("kafka数据解析异常：{}", spl);
                    return;
                }
            });
            log.info("kafka中获取到的变色龙实时数据集合:{}", logList);
            // 计算结果并存放到redis中,凌晨暂停消费数据
            if (!logList.isEmpty()) {
                pupupDataStats(logList);
            }
        });
    }

    private boolean isEffectiveDate() {
        // 当前系统时间
        Date curdate = new Date();
        Date start = DateUtil.getSpecificTime(-1, 23, 59, 00);
        Date end = DateUtil.getSpecificTime(0, 0, 0, 30);
        boolean isCon = DateUtil.isEffectiveDate(curdate, start, end);
        log.info("kafka中获取数据后是否进行后续逻辑:{}", isCon);
        return isCon;
    }

    /**
     * 转化为时间
     *
     * @param str
     * @return
     */
    private static String strToDate(String str) {
        return null == str ? str : new StringBuffer(str).insert(6, "-").insert(4, "-").toString();
    }

    /**
     * 从map中取值
     *
     * @param map
     * @param key
     * @return
     */
    private String mapGetString(Map map, String key) {
        return map.containsKey(key) && ObjectUtils.isNotEmpty(map.get(key)) ? map.get(key).toString() : null;
    }

    /**
     * @param logList
     * @return
     */
    private void pupupDataStats(List<PopupLog> logList) {
        Map<String, PopupStatistics> map = new HashMap<>(); // 存放所有
        Set<String> actSet = new HashSet<>();
        // 根据活动id分组，id作为key，对应一个PopupLog组成的list集合
        Map<String, List<PopupLog>> collect = logList.stream().collect(Collectors.groupingBy(PopupLog::getActivity_id));
        // 本次获取的数据中，活动id没有更新的数据的操作-作废，如果三分钟都没有消费数据，那么数据库会存储三分钟前的数据
        // notRefreshData(collect);
        collect.forEach((k, v) -> {
            // 以下变量为便于查看，推荐不要简写
            int reality_cnts = 0; // 当前实际下发人数
            HashSet reality_cnts_l = new HashSet(); // 当前实际下发人数集合
            int exposure_cnts = 0; // 当前曝光人数
            int exposure_times = 0; // 当前曝光次数
            HashSet exposure_cnts_l = new HashSet(); // 当前曝光人数集合
            int click_cnts = 0; // 当前点击人数
            int click_times = 0; // 当前点击次数
            HashSet click_cnts_l = new HashSet(); // 当前点击人数集合
            int close_cnts = 0; // 当前关闭人数
            int close_times = 0; // 当前关闭次数
            HashSet close_cnts_l = new HashSet(); // 当前关闭人数集合

            int reality_cnts_m = 0; // 累计实际下发人数
            int exposure_times_m = 0; // 累计曝光次数
            int exposure_cnts_m = 0; // 累计曝光人数
            int click_times_m = 0; // 累计点击次数
            int click_cnts_m = 0; // 累计点击人数
            int close_times_m = 0; // 累计关闭次数
            int close_cnts_m = 0; // 累计关闭人数

            // 此处循环是三分钟内相同活动id的计算
            for (PopupLog a : v) {
                String type = a.getEvent_type();
                switch (type) {
                    case "1":
                        reality_cnts_l.add(a.getMsisdn());
                        break;
                    case "2":
                        exposure_cnts_l.add(a.getMsisdn());
                        exposure_times++;
                        break;
                    case "3":
                        click_cnts_l.add(a.getMsisdn());
                        click_times++;
                        break;
                    case "4":
                        close_cnts_l.add(a.getMsisdn());
                        close_times++;
                        break;
                    default:
                        break;
                }
            }
            log.info("当前实际下发人数:{},当前曝光人数:{},当前点击人数:{},当前关闭人数:{}", reality_cnts_l.size(), exposure_cnts_l.size(),
                click_cnts_l.size(), close_cnts_l.size());
            log.info("当前活动id:{},当前曝光次数:{},当前点击次数:{},当前关闭次数:{}", k, exposure_times, click_times, close_times);
            String redisKey = POPUP_STATS_MIN + ":" + k;
            String redisRealityMsi = POPUP_STATS_MIN_MSI + ":" + k;
            String redisExposureMsi = "POPUP_MIN_EXP_MSI:" + k;
            String redisClickMsi = "POPUP_MIN_CLI_MSI:" + k;
            String redisCloseMsi = "POPUP_MIN_CLO_MSI:" + k;
            // 3分钟的当前人数去重
            String redisRealityMsiD = "POPUP_STATS_MIN_MSI_D:" + k;
            String redisExposureMsiD = "POPUP_MIN_EXP_MSI_D:" + k;
            String redisClickMsiD = "POPUP_MIN_CLI_MSI_D:" + k;
            String redisCloseMsiD = "POPUP_MIN_CLO_MSI_D:" + k;

            // 存放每一个活动累计用户并设置累计人数的有效时间
            if (reality_cnts_l.size() != 0) {
                redisTemplate.opsForSet().add(redisRealityMsi, reality_cnts_l.toArray());
                redisTemplate.opsForSet().add(redisRealityMsiD, reality_cnts_l.toArray());
                if (getExpireTime(redisRealityMsi) == -1) {
                    redisTemplate.expire(redisRealityMsi, expireTime(), TimeUnit.MILLISECONDS);
                }
            }
            Set<Object> realitySet = redisTemplate.opsForSet().members(redisRealityMsi);
            Set<Object> realitySetD = redisTemplate.opsForSet().members(redisRealityMsiD);
            reality_cnts = realitySetD.size();
            reality_cnts_m = realitySet.size();

            if (exposure_cnts_l.size() != 0) {
                redisTemplate.opsForSet().add(redisExposureMsi, exposure_cnts_l.toArray());
                redisTemplate.opsForSet().add(redisExposureMsiD, exposure_cnts_l.toArray());
                if (getExpireTime(redisExposureMsi) == -1) {
                    redisTemplate.expire(redisExposureMsi, expireTime(), TimeUnit.MILLISECONDS);
                }
            }
            Set<Object> exposureSet = redisTemplate.opsForSet().members(redisExposureMsi);
            Set<Object> exposureSetD = redisTemplate.opsForSet().members(redisExposureMsiD);
            exposure_cnts = exposureSetD.size();
            exposure_cnts_m = exposureSet.size();

            if (click_cnts_l.size() != 0) {
                redisTemplate.opsForSet().add(redisClickMsi, click_cnts_l.toArray());
                redisTemplate.opsForSet().add(redisClickMsiD, click_cnts_l.toArray());
                if (getExpireTime(redisClickMsi) == -1) {
                    redisTemplate.expire(redisClickMsi, expireTime(), TimeUnit.MILLISECONDS);
                }
            }
            Set<Object> clickSet = redisTemplate.opsForSet().members(redisClickMsi);
            Set<Object> clickSetD = redisTemplate.opsForSet().members(redisClickMsiD);
            click_cnts = clickSetD.size();
            click_cnts_m = clickSet.size();

            if (close_cnts_l.size() != 0) {
                redisTemplate.opsForSet().add(redisCloseMsi, close_cnts_l.toArray());
                redisTemplate.opsForSet().add(redisCloseMsiD, close_cnts_l.toArray());
                if (getExpireTime(redisCloseMsi) == -1) {
                    redisTemplate.expire(redisCloseMsi, expireTime(), TimeUnit.MILLISECONDS);
                }
            }
            Set<Object> closeSet = redisTemplate.opsForSet().members(redisCloseMsi);
            Set<Object> closeSetD = redisTemplate.opsForSet().members(redisCloseMsiD);
            close_cnts = closeSetD.size();
            close_cnts_m = closeSet.size();
            // 从redis中获取累计数据
            Object isType = redisTemplate.opsForValue().get("POPUP_STATS_MIN_TYPE:" + k);
            log.info("消费数据当前活动id:{},当前是否可以设值1:{}", k, isType);
            // 避免计算过程中出现当前id三分钟数据归零导致的数据错乱，所以采用内外双判断
            if (!"1".equals(isType)) {
                Object redis = redisTemplate.opsForValue().get(redisKey);
                if (redis != null) {
                    PopupStatistics statsRedis = JSON.parseObject(redis.toString(), PopupStatistics.class);
                    exposure_times_m = statsRedis.getExposureTimesM() + exposure_times; // 累计曝光次数
                    click_times_m = statsRedis.getClickTimesM() + click_times; // 累计点击次数
                    close_times_m = statsRedis.getCloseTimesM() + close_times; // 累计关闭次数
                    exposure_times = statsRedis.getExposureTimesD() + exposure_times; // 当前曝光次数
                    click_times = statsRedis.getClickTimesD() + click_times; // 当前点击次数
                    close_times = statsRedis.getCloseTimesD() + close_times; // 当前关闭次数
                } else {
                    exposure_times_m = exposure_times; // 累计曝光次数
                    click_times_m = click_times; // 累计点击次数
                    close_times_m = close_times; // 累计关闭次数
                }
                log.info("累计实际下发人数:{},累计曝光人数:{},累计点击人数:{},累计关闭人数:{}", reality_cnts_m, exposure_cnts_m, click_cnts_m,
                    close_cnts_m);
                log.info("当前活动id:{}累计曝光次数:{},累计点击次数:{},累计关闭次数:{}", k, exposure_times_m, click_times_m, close_times_m);
                PopupStatistics stats = new PopupStatistics(k, reality_cnts, exposure_times, exposure_cnts, click_times,
                    click_cnts, close_times, close_cnts, reality_cnts_m, exposure_times_m, exposure_cnts_m,
                    click_times_m, click_cnts_m, close_times_m, close_cnts_m);
                Object isTypes = redisTemplate.opsForValue().get("POPUP_STATS_MIN_TYPE:" + k);
                log.info("消费数据当前活动id:{},当前是否可以设值2:{}", k, isTypes);
                if (!"1".equals(isTypes)) {
                    redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(stats));
                    // 设置有效时间到每日零点
                    if (getExpireTime(redisKey) == -1) {
                        redisTemplate.expire(redisKey, expireTime(), TimeUnit.MILLISECONDS);
                    }
                }
                // 将活动id存放到set集合中
                actSet.add(k);
                log.info("当前活动id:{},当前活动id数据:{}", k, stats.toString());
            }
        });
        if (actSet.size() != 0) {
            redisTemplate.opsForSet().add(POPUP_STATS_MIN_ACT, actSet.toArray());
            /*if(getExpireTime(POPUP_STATS_MIN_ACT) == -1){
                redisTemplate.expire(POPUP_STATS_MIN_ACT,expireTime(), TimeUnit.MILLISECONDS);
            }*/
        }
        log.info("当前消费存入redis的活动id:{}", actSet.toArray());
    }

    /**
     * 当前时间到凌晨12点的时间差
     *
     * @return
     */
    private long expireTime() {
        Date currentTime = new Date();
        Date endTime = DateUtil.getDayEndTime(currentTime);
        Long expireTime = endTime.getTime() - currentTime.getTime() + 3000;
        return expireTime;
    }

    private long getExpireTime(String key) {
        return redisTemplate.opsForValue().getOperations().getExpire(key);
    }

    @Async
    public void insertKafka(ConsumerRecord<String, String> consumerRecord) {
        if (!CheckUtil.isJson(consumerRecord.value())) {
            return;
        }
        Map resultMap = JsonUtils.json2Obj(consumerRecord.value(), Map.class);
        if (resultMap != null) {
            if (CheckUtil.IsLetThrough(resultMap)) {
                KafkaInfor kafkaInfor = new KafkaInfor();
                kafkaInfor.setSendTime(System.currentTimeMillis());
                kafkaInfor.setAction(resultMap.get("action").toString());
                String objectType = resultMap.get("objectType").toString();
                kafkaInfor.setObjectType(Integer.parseInt(objectType));
                // 1：歌曲 2:专辑 5：MV素材
                // 3：艺术家 4：数字专辑 6：咪咕爱唱素材(暂未实现) 7：短视频素材 8：视频彩铃素材
                String material;
                String artistList;
                JSONArray jsonArray;
                // 1：歌曲 2:专辑 5：MV素材
                // 3：艺术家 4：数字专辑 6：咪咕爱唱素材(暂未实现) 7：短视频素材 8：视频彩铃素材
                switch (objectType) {
                    case "1":
                        // 解析歌曲对象
                        material = resultMap.get("material").toString();
                        Map songResultMap = JsonUtils.json2Obj(material, Map.class);
                        // 歌曲Id
                        String songId = songResultMap.get("songId").toString();
                        if (songResultMap.get("releaseDate") != null) {
                            String releaseSongDate = songResultMap.get("releaseDate").toString();
                            // 歌曲的发行日期需要在三个月内
                            if (DateUtil.IsIndwell(releaseSongDate, 3)) {
                                return;
                            }
                        }
                        // 获取艺人列表
                        artistList = songResultMap.get("artistList").toString();
                        // 转json 数组
                        jsonArray = JSONArray.parseArray(artistList);
                        String singerId = null;
                        String singerName = null;
                        for (int i = 0; i < jsonArray.size(); i++) {
                            Map artistResultMap = JsonUtils.json2Obj(jsonArray.get(i).toString(), Map.class);
                            String artistId = artistResultMap.get("artistId").toString();
                            singerId = artistId.concat(",");
                            // 获取艺人姓名 可以为空
                            String name = artistResultMap.get("name").toString();
                            singerName = name.concat(",");
                        }
                        if (StringUtils.isNotBlank(singerId) && singerId.endsWith(",")) {
                            singerId = singerId.substring(0, singerId.length() - 1);
                        }
                        if (StringUtils.isNotBlank(singerName) && singerName.endsWith(",")) {
                            singerName = singerName.substring(0, singerName.length() - 1);
                        }
                        kafkaInfor.setSourceId(songId);
                        kafkaInfor.setSingerId(singerId);
                        kafkaInfor.setSingerName(singerName);
                        String songName = songResultMap.get("songName").toString();
                        kafkaInfor.setSourceName(songName);
                        break;
                    case "2":
                        material = resultMap.get("material").toString();
                        Map albumResultMap = JsonUtils.json2Obj(material, Map.class);
                        String albumId = albumResultMap.get("albumId").toString();
                        // 获取艺人列表
                        artistList = albumResultMap.get("artistList").toString();
                        if (albumResultMap.get("publishDate") != null) {
                            String publishDate = albumResultMap.get("publishDate").toString();
                            // 专辑的发行日期需要在三个月内
                            if (DateUtil.IsIndwell(publishDate, 3)) {
                                return;
                            }
                        }
                        // 转json 数组
                        jsonArray = JSONArray.parseArray(artistList);
                        String albumerId = null;
                        String albumName = null;
                        for (int i = 0; i < jsonArray.size(); i++) {
                            Map artistResultMap = JsonUtils.json2Obj(jsonArray.get(i).toString(), Map.class);
                            String artistId = artistResultMap.get("artistId").toString();
                            albumerId = artistId.concat(",");
                            // 获取艺人姓名 可以为空
                            String name = artistResultMap.get("name").toString();
                            albumName = name.concat(",");
                        }
                        if (StringUtils.isNotBlank(albumerId) && albumerId.endsWith(",")) {
                            albumerId = albumerId.substring(0, albumerId.length() - 1);
                        }
                        if (StringUtils.isNotBlank(albumName) && albumName.endsWith(",")) {
                            albumName = albumName.substring(0, albumName.length() - 1);
                        }
                        String albumNames = albumResultMap.get("albumName").toString();
                        kafkaInfor.setSourceId(albumId);
                        kafkaInfor.setSingerId(albumerId);
                        kafkaInfor.setSingerName(albumName);
                        kafkaInfor.setSourceName(albumNames);
                        break;
                    case "5":
                        material = resultMap.get("material").toString();
                        Map mvResultMap = JsonUtils.json2Obj(material, Map.class);
                        String mvId = mvResultMap.get("id").toString();
                        String mvName = mvResultMap.get("name").toString();
                        String singgers = mvResultMap.get("singers").toString();
                        // 只取mvType=0的数据
                        String mvType = mvResultMap.get("mvType").toString();
                        if (mvResultMap.get("releaseDate") != null) {
                            String releaseMvDate = mvResultMap.get("releaseDate").toString();
                            // mv的发行日期需要在三个月内
                            if (DateUtil.IsIndwell(releaseMvDate, 3)) {
                                return;
                            }
                        }
                        // mv的mvType只取0
                        if (!"0".equals(mvType)) {
                            return;
                        }
                        // 存储歌手id
                        kafkaInfor.setObjectType(CatalogInfoEnum.TOWIRELESSPRODUCT.getCode());
                        kafkaInfor.setSingerId(singgers);
                        kafkaInfor.setSourceId(mvId);
                        kafkaInfor.setSourceName(mvName);
                        break;
                    default:
                        break;
                }
                // 判断是否有敏感词汇 有为true 没有为false
                Boolean IsTacful =
                    autoTouchOffMapper.selectSourceNameTacful(kafkaInfor.getSourceName()) > 0 ? true : false;
                if (!IsTacful) {
                    int sourceId = 0;
                    if (StringUtils.isNotBlank(kafkaInfor.getSourceId())) {
                        sourceId = Integer.parseInt(kafkaInfor.getSourceId());
                    }
                    // 主要是可能存在多个歌手
                    List<SinggerResource> list = SinggerResourceLists(kafkaInfor.getObjectType(),
                        kafkaInfor.getSingerId(), sourceId, kafkaInfor.getSourceName());
                    if (list != null && !list.isEmpty()) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("list", list);
                        autoTouchOffMapper.insertBatchSinggerResource(map);
                    }
                }
            }
        }
    }

    /**
     * 构造list
     *
     * @param objectType
     * @param singerId
     * @param sourceId
     * @return
     */
    public List<SinggerResource> SinggerResourceLists(int objectType, String singerId, int sourceId,
        String sourceName) {
        List<SinggerResource> list = Lists.newArrayList();
        RelationEnum relationEnum = RelationEnum.getValueByKey(objectType);
        String relationName = relationEnum.getMessage();
        int relationType = relationEnum.getCode().intValue();
        int grade = relationEnum.getGrade().intValue();
        // SEND_END_TIME
        int total = differenceTimes(SEND_END_TIME);
        log.info("-----------判断入库时间是否距离晚上截止时间21:00 分钟数:{}", total);
        String sendDate;
        if (total > 0) {
            // 今天
            sendDate = LocalDate.now().toString();
        } else {
            // 明天
            sendDate = LocalDate.now().plusDays(1).toString();
        }
        SinggerResource singgerResource;
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(singerId)) {
            String singerName;
            if (singerId.contains(",")) {
                String[] singerIds = singerId.split(",");
                for (int i = 0; i < singerIds.length; i++) {
                    singerName = singerName(singerIds[i]);
                    if (grade > 0 && com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(singerName)) {
                        singgerResource = new SinggerResource(singerIds[i], singerName, sourceId, sourceName,
                            relationType, relationName, grade, sendDate);
                        list.add(singgerResource);
                    }
                }
            } else {
                singerName = singerName(singerId);
                if (grade > 0 && com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(singerName)) {
                    singgerResource = new SinggerResource(singerId, singerName, sourceId, sourceName, relationType,
                        relationName, grade, sendDate);
                    list.add(singgerResource);
                }
            }
        }
        return list;
    }

    /**
     * 根据歌手id 查询歌手名称
     *
     * @param singerId
     * @return
     */
    private String singerName(String singerId) {
        return autoTouchOffMapper.getSingerName(singerId);
    }

    /**
     * @param endTimes
     * @return
     */
    private static int differenceTimes(String endTimes) {
        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        try {
            LocalDateTime localDateTime = LocalDateTime.now();
            String date1 = dtf2.format(localDateTime).substring(0, 16);
            String date2 = LocalDate.now().toString().concat(" ").concat(endTimes);
            Date fromDate2 = simpleFormat.parse(date1);
            Date toDate2 = simpleFormat.parse(date2);
            long from3 = fromDate2.getTime();
            long to3 = toDate2.getTime();
            int minutes = (int)((to3 - from3) / (1000 * 60));
            return minutes;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
